<template>
  <!-- 没有将组件放在components里导致要重新写 -->
  <div class='order container'>
    <header>
      <i
        class='iconfont icon-fanhui'
        @click='$router.back()'
      ></i>
      <span>提交订单</span>
      <i class='iconfont icon-kefu'></i>
    </header>
    <section>
      <div class='path'>
        <h3
          class='path-title'
          @click="goPath"
        >收货信息</h3>
        <div
          class='path-content'
          @click="goPath"
        >
          <div>
            <span>{{path.name}}</span>
            <span>{{path.tel}}</span>
          </div>
          <div>
            <span>{{path.province}}</span>
            <span>{{path.city}}</span>
            <span>{{path.county}}</span>
            <span>{{path.addressDetail}}</span>
          </div>
        </div>
      </div>
      <div class='payment'>
        <!-- 支付的方式，支付沙箱 测试版本 无需认证 -->
        <div class='payment-title'>支付方式：<span>推荐使用支付宝购买,随机立减0
            <!-- {{path.province}} -->元
          </span>
        </div>
        <!--
          div
          class='payment-title'
        >支付方式：
      </div> -->
        <van-radio-group v-model="radioPayment">
          <van-radio name="wx">微信支付</van-radio>
          <van-radio name="ali">支付宝支付</van-radio>
        </van-radio-group>
      </div>
      <div class='goods'>

        <!-- 之前的代码注释 -->
        <ul>
          <li
            v-for='(item,index) in goodsList'
            :key='index'
          >
            <!-- //报错 goods_imgUrl 的原因是刷新后 goodsList 不存在 无法遍历 -->
            <div>
              <img
                :src="item.goods_imgUrl"
                alt=""
              >
            </div>
            <div class='goods-content'>
              <h4>{{item.goods_name}}</h4>
              <div class='goods-total'>
                <span>¥{{item.goods_price}}</span>
                <span>x{{item.goods_num}}</span>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </section>
    <footer>
      <div class='order-total'>
        <span>共</span>
        <b>{{total.num}}</b>
        <span>件,</span>
        <span>总金额：</span>
        <em>¥{{total.price}}</em>
      </div>
      <div
        class='order-topay'
        @click="goPayment"
      >
        提交订单
      </div>
    </footer>
  </div>
</template>
<script>
import http from "@/common/api/request.js";
import { Toast } from "mint-ui";
import { mapState, mapGetters, mapMutations } from "vuex";
import bus from "../common/bus.js";
import qs from "qs";
export default {
  data() {
    return {
      radioPayment: "ali",
      path: {},
      item: [],
      total: {
        price: 0,
        num: 0,
      },
    };
  },
  computed: {
    //注释 不能用
    /*     ...mapState({
      list: (state) => state.cart.list,
    }), */
    ...mapState({
      /* list: (state) => state.order.list, */
      order_id: (state) => state.order.order_id, //订单号
      selectList: (state) => state.cart.selectList,
    }),
    //...mapGetters(["total", "defaultPath"]),total在引用的同时也调用了
    ...mapGetters(["defaultPath"]),
    //新加
    /*     goodsList() {
      return this.item.map((id) => {
        return this.list.find((v) => v.id == id);
      });
    }, */
    //注释 不能用
    /* 移动到Cart里    goodsList() {
      return this.item.map((id) => {
        //console.log(id);
        //console.log(this.list);=》验证刷新的list
        return this.list.find((v) => v.id == id);
        //this.list. =》 这个 ...mapState({list: (state) => state.cart.list,}), 这个list 式通过cart.js来的
        //cart是购物车页面，赋值的，如果在结算页面直接刷新，没有，那么怎么能有值呢？
      });
        }, */
  },
  //http://localhost:8080/order?detail=%5B64,40%5D 传输出现问题，应该隐式传递

  //显式可以把数据挂载到URL上
  created() {
    //放在生命周期里了
    /*     bus.$on(
      "selectPath",
      function (data) {
        this.path = JSON.parse(data);
        console.log(JSON.parse(data), "data");
      }.bind(this)
    ); */

    //console.log(JSON.parse(this.$route.query.detail));
    //选中的商品id号
    this.goodsList = JSON.parse(this.$route.query.goodsList);
    //this.item = JSON.parse(this.$route.query.detail);//接收显示传递的  不用这个了
    //console.log(this.$route);
    //↓接收隐式传递的
    //this.item = JSON.parse(this.$route.params.detail);//用了这句距activated那句就不起效了
    this.selectAddress(); //封装在  methods
  },
  //生命周期 keepalive缓存
  activated() {
    bus.$on(
      "selectPath",
      function (data) {
        this.path = JSON.parse(data);
      }.bind(this)
    );
    //选中的商品id号
    this.item = JSON.parse(this.$route.query.detail);
    this.goodsList = JSON.parse(this.$route.query.goodsList);
    this.selectOrder();
  },
  methods: {
    ...mapMutations(["initData", "initOrder"]), //initOrder再存储一遍

    //发送请求请求收货地址
    //查询地址
    selectAddress() {
      http
        .$axios({
          url: "/api/selectAddress",
          method: "post",
          headers: {
            token: true,
          },
        })
        .then((res) => {
          //console.log(res);
          this.initData(res.data); //把这个值传过去，然后vuex里面的就有数据 state.list
          //有默认收货地址
          if (this.defaultPath.length) {
            this.path = this.defaultPath[0]; //有则选择收货地址
          } else {
            this.path = res.data[0]; //无则选择第一个
          }
        });
    },
    //！！！！！！！！！！！！！！
    //查询订单 请求
    selectOrder() {
      http
        .$axios({
          url: "/api/selectOrder",
          method: "post",
          headers: {
            token: true,
          },
          data: {
            //通过orderId订单号去查询订单
            orderId: this.order_id,
          },
        })
        .then((res) => {
          this.initOrder(res.data);

          //this.total.price = res.data[0].goods_price;
          //this.total.num = res.data[0].goods_num;
          //另一种写法
          this.total = {
            price: res.data[0].goods_price,
            num: res.data[0].goods_num,
          };
        });
    },

    //提交订单
    goPayment() {
      Toast("订单提交中");
      if (!this.path) {
        //判断是否选择收货地址
        //没有赋值为 path:[],
        Toast("您还没有登录呢..跳转到登录页面中");
        this.$router.push("/login");
        return;
      }
      //发送请求==》1.修改订单状态2.删除购物车的数据
      http
        .$axios({
          url: "/api/submitOrder",
          method: "post",
          headers: {
            token: true,
            /*"content-type": "appliocation/x-form-urlencoded", 
            提交的时候是不需要的
            支付的时候是需要的
            */
          },
          data: {
            orderId: this.order_id,
            shopArr: this.selectList,
          },
        })
        .then((res) => {
          let newArr = [];
          this.goodsList.forEach((v) => {
            newArr.push(v.goods_name);
          });
          //支付传递的参数
          let dataOrder = {
            orderId: this.order_id,
            //name: this.goodsList.goods_name,
            name: newArr.join(""), //解析成字符串
            price: this.total.price,
          };

          if (res.success) {
            //如果是对的，再发送一个请求//对接支付宝沙箱
            //去支付
            http
              .$axios({
                url: "/api/payment",
                method: "post",
                headers: {
                  token: true,
                  //涉及到支付，必须要像下面这样写
                  /*"content-type": "appliocation/  x-form-urlencoded", 
                      提交的时候是不需要的
                      支付的时候是需要的
            */
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                /* data: {  （dataOrder） 不能随便传
                  orderId: this.order_id,  要用vue qs
                  shopArr: this.selectList,
                }, 
                qs是一个增加了一些安全性的查询字符串解析和序列化字符串的库=》参数序列化
                js.stringify 不安全 vue qs 安全
                */
                //qs增加安全性的序列化
                data: qs.stringify(dataOrder), //QueryString
              })
              .then((res) => {
                //返回链接 跳转支付宝
                //console.log(res); //返回的是url
                //windows.location.href
                //windows.open(res),
                if (res.success) {
                  //打开支付宝支付的页面
                  window.location.href = res.paymentUrl;
                }
              });
          }
          console.log(res);
        });
    },
    //选择收获地址//跳转到收货地址//不单单是单纯的跳转
    /*     goPath() {
      this.$router.push("/path");
    }, */
    goPath() {
      this.$router.push({
        path: "/path",
        query: {
          type: "select",
        },
      });
    },
  },
};
</script>

<style lang='scss' scoped>
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 1.173333rem;
  color: #fff;
  background-color: #b0352f;
  i {
    padding: 0 0.4rem;
    font-size: 0.586666rem;
  }
  span {
    font-weight: 300;
    font-size: 0.48rem;
  }
}
section {
  background-color: #f7f7f7;
  .path-title {
    padding: 0.4rem;
    font-size: 0.48rem;
  }
  .path-content {
    padding: 0.16rem 0.4rem;
    font-size: 0.373333rem;
    background-color: #ffffff;
    span {
      padding-right: 0.16rem;
    }
  }

  .payment {
    padding: 0.16rem 0.4rem;
    margin-top: 0.4rem;
    font-size: 0.426666rem;
    background-color: #ffffff;
    .van-radio-group {
      //点击框的样式
      display: flex;
      padding: 0.16rem 0.5rem;
      .van-radio {
        padding-right: 0.566666rem;
      }
    }
    .payment-title {
      padding-right: 0.16remx;
      span {
        padding-left: 0.5rem;
        color: orange;
      }
    }
  }
  .goods {
    padding: 0.16rem 0.4rem;
    margin-top: 0.4rem;
    font-size: 0.426666rem;
    background-color: #ffffff;
    ul {
      width: 98%;
      li {
        display: flex;
        width: 90vw;
        align-items: center;
        img {
          width: 1.973333rem;
          height: 1.973333rem;
        }
        .goods-content {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding-left: 0.4rem;
          .goods-total {
            display: flex;
            justify-content: space-between;
          }
        }
      }
    }
  }
}
footer {
  padding: 0rem 2vw;
  padding-left: 2vw;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 98vw;
  height: 1.2rem;
  border-top: 1px solid #ccc;
  .order-total {
    font-size: 0.426666rem;
    span {
      padding: 0 0.16rem;
    }
    b,
    em {
      color: #b0352f;
    }
    em {
      font-size: 0.48rem;
    }
  }
  .order-topay {
    width: 3.2rem;
    line-height: 1.2rem;
    color: #fff;
    font-size: 0.426666rem;
    text-align: center;
    background-color: #b0352f;
  }
}
</style>
